using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
//添加的命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConferenceSystem
{
	public class UdpCommandBroadcast : IDisposable
	{
		UdpClient myUdpclient = null;
		
		//使用的接收端口 51008
        /// <summary>
        /// 端口号
        /// </summary>
        private int port = 51008;

        /// <summary>
        /// udp连接对象
        /// </summary>
        private UdpClient udpclient;
		
		public void SendCommand(string text)
		{
            try
            {
                IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, port);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);
                myUdpclient.Send(bytes, bytes.Length, iep);
            }
            catch (Exception err)
            {
                //MessageBox.Show(err.Message, "发送失败");
            }
            finally
            {
                myUdpclient.Close();
            }
		}
		
        delegate void AppendStringCallback(string text);
        AppendStringCallback appendstringcallback;
		
		public UdpCommandBroadcast ()
		{
			appendstringcallback = new AppendStringCallback(AppendString);
			myUdpclient = new UdpClient();
		}

        /// <summary>
        /// 委托对象的处理过程
        /// </summary>
        /// <param name="text"></param>
        private void AppendString(string text)
        {
//            if (richtextBox2.InvokeRequired == true)
//            {
//                this.Invoke(appendstringcallback, text);
//            }
//            else
//            {
//                richtextBox2.AppendText(text + "\r\n");
//            }
        }

        /// <summary>
        /// 在后台运行的接收线程
        /// </summary>
        private void RecData()
        {
            //本机指定端口接收
            udpclient = new UdpClient(port);
            IPEndPoint remote = null;
            //接收从远程主机发送过来的信息
            while (true)
            {
                try
                {
                    //关闭udpclient时此句会产生异常
                    byte[] bytes = udpclient.Receive(ref remote);
                    string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                    //AppendString(string.Format("来自{0}:{1}", remote, str));
                }
                catch
                {
                    //退出循环,结束线程
                    break;
                }
            }
        }

		#region IDisposable implementation
		public void Dispose ()
		{
			udpclient.Close ();
			myUdpclient.Close ();
		}
		#endregion
    }
}

